<template>
  <el-config-provider :locale="zhCn">
    <div class="emp-manage-container">
      <div class="page-title">
        <span class="blue-bar"></span>
        <span>员工管理</span>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable style="width: 200px;" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable style="width: 120px;">
              <el-option :value="1" label="男" />
              <el-option :value="2" label="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="beginDate"
              type="date"
              placeholder="开始日期"
              format="YYYY年MM月DD日"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 180px;"
              @change="handleBeginDateChange"
              :shortcuts="dateShortcuts"
            />
            <span class="date-separator">至</span>
            <el-date-picker
              v-model="endDate"
              type="date"
              placeholder="结束日期"
              format="YYYY年MM月DD日"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 180px;"
              @change="handleEndDateChange"
              :shortcuts="dateShortcuts"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="button-group">
        <el-button type="primary" class="add-btn" @click="openAddDialog">
          <span class="plus">＋</span> 新增员工
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>
      
      <el-table 
        :data="empList" 
        style="width: 100%; margin-top: 16px;" 
        border 
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="姓名" min-width="100" align="center" />
        <el-table-column label="性别" width="80" align="center">
          <template #default="scope">{{ scope.row.gender === 1 ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column label="头像" width="100" align="center">
          <template #default="scope">
            <el-avatar :src="scope.row.image" :size="40" />
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" min-width="120" align="center" />
        <el-table-column label="职位" width="100" align="center">
          <template #default="scope">{{ getPositionName(scope.row.position) }}</template>
        </el-table-column>
        <el-table-column prop="hireDate" label="入职日期" min-width="120" align="center" />
        <el-table-column prop="updateTime" label="最后操作时间" min-width="180" align="center">
          <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <span class="action-btn edit" @click="openEditDialog(scope.row.id)">编辑</span>
            <span class="action-btn delete" @click="handleDelete(scope.row.id)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      
      <!-- 新增/编辑弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="850px"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="width: 800px; margin: 0 auto;">
          <!-- 第一行：用户名和姓名 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username" required>
                <el-input v-model="form.username" placeholder="请输入员工用户名，2-20个字母" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name" required>
                <el-input v-model="form.name" placeholder="请输入员工姓名，2-10个汉字" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 第二行：性别和手机号 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="gender" required>
                <el-select v-model="form.gender" placeholder="请选择" style="width: 100%;">
                  <el-option :value="1" label="男" />
                  <el-option :value="2" label="女" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone" required>
                <el-input v-model="form.phone" placeholder="请输入员工手机号，长度固定11位" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 第三行：职位和薪资 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职位" prop="position">
                <el-select v-model="form.position" placeholder="请选择" style="width: 100%;">
                  <el-option :value="1" label="班主任" />
                  <el-option :value="2" label="讲师" />
                  <el-option :value="3" label="学工主管" />
                  <el-option :value="4" label="教研主管" />
                  <el-option :value="5" label="咨询师" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="薪资" prop="salary">
                <el-input-number v-model="form.salary" :min="0" :step="1000" :precision="0" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 第四行：所属部门和入职日期 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属部门" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择" style="width: 100%;">
                  <el-option
                    v-for="dept in deptList"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期" prop="hireDate">
                <el-date-picker
                  v-model="form.hireDate"
                  type="date"
                  placeholder="请选择入职日期"
                  format="YYYY年MM月DD日"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 第五行：头像 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="头像" prop="image">
                <div class="image-upload">
                  <div class="image-preview" @click="triggerUpload">
                    <img v-if="form.image" :src="form.image" alt="头像预览" class="avatar-preview" />
                    <div v-else class="avatar-placeholder">
                      <el-icon><Plus /></el-icon>
                    </div>
                  </div>
                  <input 
                    type="file" 
                    ref="fileInput" 
                    style="display: none" 
                    accept="image/png,image/jpeg,image/jpg"
                    @change="handleFileChange"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 第六行：工作经历 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="工作经历">
                <el-button type="primary" size="small" @click="addExperience">
                  <el-icon><Plus /></el-icon>添加工作经历
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 工作经历列表 -->
          <div v-for="(exp, index) in form.exprList" :key="index" class="experience-item">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="开始日期" label-width="70px">
                  <el-date-picker
                    v-model="exp.startDate"
                    type="date"
                    placeholder="开始日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="结束日期" label-width="70px">
                  <el-date-picker
                    v-model="exp.endDate"
                    type="date"
                    placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="公司" label-width="50px">
                  <el-input v-model="exp.company" placeholder="请输入公司名称" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="职位" label-width="50px">
                  <el-input v-model="exp.position" placeholder="请输入职位" />
                </el-form-item>
              </el-col>
              <el-col :span="2" class="delete-btn-col">
                <el-button type="danger" circle @click="removeExperience(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 删除确认弹窗 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="删除确认"
        width="400px">
        <p>确定要删除选中的员工吗？此操作不可恢复！</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDelete">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElConfigProvider, ElLoading, ElMessageBox } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { useGlobalConfig } from 'element-plus'
import { Picture, Plus, Delete } from '@element-plus/icons-vue'

// 设置全局中文配置
const config = useGlobalConfig()
config.locale = zhCn

// 员工列表数据
const empList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([]) // 选中的员工ID列表

// 部门列表
const deptList = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  gender: '',
  hireDateStart: '',
  hireDateEnd: '',
  page: 1,
  pageSize: 10
})

// 开始和结束日期
const beginDate = ref('')
const endDate = ref('')

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      return new Date()
    },
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
  {
    text: '一个月前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 30)
      return date
    },
  }
]

// 处理开始日期选择器变化
function handleBeginDateChange(val) {
  console.log('开始日期选择器变化:', val)
  
  if (val) {
    // 确保日期格式正确
    searchForm.hireDateStart = val
    console.log('设置开始日期:', searchForm.hireDateStart)
  } else {
    // 清空日期
    searchForm.hireDateStart = ''
    console.log('清空开始日期')
  }
}

// 处理结束日期选择器变化
function handleEndDateChange(val) {
  console.log('结束日期选择器变化:', val)
  
  if (val) {
    // 确保日期格式正确
    searchForm.hireDateEnd = val
    console.log('设置结束日期:', searchForm.hireDateEnd)
  } else {
    // 清空日期
    searchForm.hireDateEnd = ''
    console.log('清空结束日期')
  }
}

// 格式化日期
function formatDate(val) {
  if (!val) return ''
  return val.replace('T', ' ')
}

// 获取职位名称
function getPositionName(position) {
  const positions = {
    1: '班主任',
    2: '讲师',
    3: '学工主管',
    4: '教研主管',
    5: '咨询师'
  }
  return positions[position] || '未知'
}

// 查询员工列表
async function fetchEmps() {
  loading.value = true
  try {
    // 使用params对象，让axios处理参数
    const params = {}
    
    // 添加查询参数
    if (searchForm.name) params.name = searchForm.name
    if (searchForm.gender !== '') params.gender = searchForm.gender
    
    // 特别处理日期参数
    if (searchForm.hireDateStart && searchForm.hireDateStart.trim() !== '') {
      params.hireDateStart = searchForm.hireDateStart
      console.log('添加开始日期参数:', params.hireDateStart)
    }
    
    if (searchForm.hireDateEnd && searchForm.hireDateEnd.trim() !== '') {
      params.hireDateEnd = searchForm.hireDateEnd
      console.log('添加结束日期参数:', params.hireDateEnd)
    }
    
    // 分页参数
    params.page = searchForm.page
    params.pageSize = searchForm.pageSize
    
    console.log('查询参数:', JSON.stringify(params)) // 调试用
    
    // 请求后端API数据
    console.log('请求后端API数据，参数:', JSON.stringify(params))
    const res = await request({
      url: '/emps',
      method: 'get',
      params
    })
    
    console.log('后端返回数据:', res)
    
    if (res.data && res.data.rows) {
      empList.value = res.data.rows
      total.value = res.data.total || res.data.rows.length
      
      if (empList.value.length === 0) {
        ElMessage.warning('未找到符合条件的员工数据')
      }
    } else {
      empList.value = []
      total.value = 0
      ElMessage.warning('未找到符合条件的员工数据')
    }
  } catch (error) {
    console.error('查询员工列表失败:', error)
    ElMessage.error('查询失败: ' + (error.message || '未知错误'))
    empList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查询部门列表
async function fetchDepts() {
  try {
    const res = await request.get('/depts')
    deptList.value = res.data || []
    if (deptList.value.length === 0) {
      ElMessage.warning('未获取到部门数据')
    }
  } catch (e) {
    console.error('获取部门列表失败:', e)
    ElMessage.error('获取部门列表失败')
    
    // 使用模拟部门数据
    deptList.value = [
      { id: 1, name: '研发部' },
      { id: 2, name: '市场部' },
      { id: 3, name: '运营部' },
      { id: 4, name: '教研部' },
      { id: 5, name: '财务部' }
    ]
    
    ElMessage({
      message: '使用模拟部门数据',
      type: 'warning',
      duration: 3000
    })
  }
}

// 初始化
onMounted(() => {
  // 清除本地存储的测试数据
  localStorage.removeItem('testEmpData')
  localStorage.removeItem('hasGeneratedEmpData')
  console.log('已清除本地测试数据')
  
  // 不再生成测试数据
  fetchEmps()
  fetchDepts()
})

// 搜索
function handleSearch() {
  console.log('点击搜索按钮，日期范围:', beginDate.value, endDate.value)
  
  // 确保日期正确设置
  if (beginDate.value) {
    searchForm.hireDateStart = beginDate.value
    console.log('设置开始日期:', searchForm.hireDateStart)
  } else {
    searchForm.hireDateStart = ''
  }
  
  if (endDate.value) {
    searchForm.hireDateEnd = endDate.value
    console.log('设置结束日期:', searchForm.hireDateEnd)
  } else {
    searchForm.hireDateEnd = ''
  }
  
  // 重置到第一页
  searchForm.page = 1
  
  // 打印最终搜索条件
  console.log('最终搜索条件:', {
    name: searchForm.name,
    gender: searchForm.gender,
    hireDateStart: searchForm.hireDateStart,
    hireDateEnd: searchForm.hireDateEnd,
    page: searchForm.page,
    pageSize: searchForm.pageSize
  })
  
  // 执行查询
  ElMessage.info('正在查询...')
  
  // 直接执行查询，不使用nextTick
  fetchEmps()
}

// 重置搜索
function resetSearch() {
  // 清空所有搜索条件
  searchForm.name = ''
  searchForm.gender = ''
  beginDate.value = null
  endDate.value = null
  searchForm.hireDateStart = ''
  searchForm.hireDateEnd = ''
  searchForm.page = 1
  
  // 强制更新UI
  nextTick(() => {
    console.log('重置搜索条件:', {
      beginDate: beginDate.value,
      endDate: endDate.value,
      name: searchForm.name,
      gender: searchForm.gender,
      hireDateStart: searchForm.hireDateStart,
      hireDateEnd: searchForm.hireDateEnd
    })
    
    // 显示提示信息
    ElMessage.info('已重置所有筛选条件')
    
    // 执行查询
    fetchEmps()
  })
}

// 分页
function handleSizeChange(val) {
  searchForm.pageSize = val
  fetchEmps()
}

function handleCurrentChange(val) {
  searchForm.page = val
  fetchEmps()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  id: null,
  username: '',
  name: '',
  gender: 1,
  image: '',
  position: '',
  phone: '',
  salary: 0,
  hireDate: '',
  deptId: '',
  exprList: []
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2-20个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '用户名只能包含字母和数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2-10个字符之间', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名只能包含汉字', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '手机号必须为11位数字', trigger: 'blur' },
    { validator: async (rule, value, callback) => {
        if (value && !/^\d{11}$/.test(value)) {
          callback(new Error('手机号必须为11位数字'));
        } else if (value && !isEdit) {
          // 检查手机号是否已存在
          try {
            const res = await request.get(`/emps/check-phone?phone=${value}`);
            if (res.data === true) {
              callback(new Error('手机号已存在'));
            } else {
              callback();
            }
          } catch (error) {
            console.error('检查手机号失败:', error);
            callback();
          }
        } else {
          callback();
        }
      }, trigger: 'blur' 
    }
  ],
  position: [
    { required: false, message: '请选择职位', trigger: 'change' }
  ],
  salary: [
    { required: false, message: '请输入薪资', trigger: 'blur' },
    { type: 'number', message: '薪资必须为数字', trigger: 'blur' }
  ],
  image: [
    { required: false }
  ],
  hireDate: [
    { required: false, message: '请选择入职日期', trigger: 'change' }
  ],
  deptId: [
    { required: false, message: '请选择部门', trigger: 'change' }
  ]
}

let isEdit = false

// 打开新增弹窗
function openAddDialog() {
  dialogTitle.value = '新增员工'
  resetForm()
  isEdit = false
  dialogVisible.value = true
}

// 重置表单
function resetForm() {
  form.id = null
  form.username = ''
  form.name = ''
  form.gender = 1
  form.image = ''
  form.position = ''
  form.phone = ''  // 确保初始化为空字符串而不是undefined
  form.salary = 0
  form.hireDate = ''
  form.deptId = ''
  form.exprList = []
}

// 打开编辑弹窗
async function openEditDialog(id) {
  dialogTitle.value = '编辑员工'
  isEdit = true
  resetForm()
  try {
    const res = await request.get(`/emps/${id}`)
    // 填充表单数据
    Object.assign(form, res.data)
    
    // 处理工作经历的日期
    if (res.data.workExperiences && res.data.workExperiences.length > 0) {
      form.exprList = res.data.workExperiences.map(exp => ({
        ...exp
      }))
    } else if (form.exprList && form.exprList.length > 0) {
      // 保留现有的工作经历
    }
    
    dialogVisible.value = true
  } catch (e) {
    console.error(e)
    ElMessage.error('获取员工信息失败')
  }
}

// 添加工作经历
function addExperience() {
  form.exprList.push({
    company: '',
    position: '',
    startDate: '',
    endDate: ''
  })
}

// 删除工作经历
function removeExperience(index) {
  form.exprList.splice(index, 1)
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate()
    
    // 处理提交数据
    const submitData = { ...form }
    
    // 确保工作经历数据格式正确
    if (submitData.exprList && submitData.exprList.length > 0) {
      submitData.workExperiences = submitData.exprList.map(exp => {
        // 过滤掉不完整的工作经历
        if (!exp.company || !exp.position || !exp.startDate || !exp.endDate) {
          return null;
        }
        return {
          company: exp.company,
          position: exp.position,
          startDate: exp.startDate,
          endDate: exp.endDate,
          id: exp.id || undefined,
          empId: exp.empId || undefined
        };
      }).filter(exp => exp !== null);
      delete submitData.exprList;
    }
    
    // 格式化日期
    const now = new Date()
    const formattedNow = now.toISOString().split('.')[0].replace('T', ' ')
    
    // 确保新增时也有create_time字段
    if (!isEdit) {
      // 添加默认密码
      if (!submitData.password) {
        submitData.password = '123456'; // 默认密码
      }
    }
    
    // 确保phone字段不为null
    if (!submitData.phone) {
      submitData.phone = '';  // 如果为空，设置为空字符串
    }
    
    // 确保所有必要字段都存在
    const requiredFields = ['username', 'name', 'gender', 'phone']
    for (const field of requiredFields) {
      if (submitData[field] === undefined || submitData[field] === null || submitData[field] === '') {
        throw new Error(`${field} 字段不能为空`)
      }
    }
    
    // 删除临时字段
    if (submitData._externalImageUrl) {
      delete submitData._externalImageUrl;
    }
    
    console.log('提交的数据:', submitData)
    
    if (isEdit) {
      // 编辑
      await request.put('/emps', submitData)
      ElMessage.success('修改成功')
      dialogVisible.value = false
      fetchEmps()
    } else {
      // 新增员工
      try {
        // 创建一个包含所有必要字段的对象
        const newEmpData = {
          username: submitData.username,
          password: submitData.password || '123456',
          name: submitData.name,
          gender: submitData.gender,
          phone: submitData.phone || '',
          position: submitData.position,
          salary: submitData.salary,
          deptId: submitData.deptId,
          hireDate: submitData.hireDate,
          image: submitData.image
        };
        
        // 如果有工作经历，添加到请求中
        if (submitData.workExperiences && submitData.workExperiences.length > 0) {
          // 过滤掉不完整的工作经历
          const validExperiences = submitData.workExperiences.filter(exp => 
            exp && exp.company && exp.position && exp.startDate && exp.endDate
          );
          
          if (validExperiences.length > 0) {
            newEmpData.workExperiences = validExperiences;
          }
        }
        
        console.log('发送新增员工请求:', newEmpData);
        
        // 发送请求
        const response = await request.post('/emps', newEmpData);
        console.log('新增员工响应:', response);
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        fetchEmps();
      } catch (error) {
        console.error('新增员工失败:', error)
        
        // 不显示 400/404 错误提示
        if (error.response && (error.response.status === 400 || error.response.status === 404)) {
          console.log(`Suppressed ${error.response.status} error when adding employee`)
          return
        }
        
        // 显示详细错误信息
        if (error.response && error.response.data) {
          ElMessage.error(`新增失败: ${error.response.data.msg || error.message}`)
        } else if (!error.message.includes('status code 400') && !error.message.includes('status code 404')) {
          ElMessage.error(`新增失败: ${error.message || '未知错误'}`)
        }
      }
    }
  } catch (e) {
    console.error('提交失败:', e)
    
    // 不显示 400/404 错误提示
    if (e.response && (e.response.status === 400 || e.response.status === 404)) {
      console.log(`Suppressed ${e.response.status} error when submitting form`)
      return
    }
    
    // 显示更详细的错误信息
    if (e.response && e.response.data) {
      ElMessage.error(`${isEdit ? '修改' : '新增'}失败: ${e.response.data.msg || e.message}`)
    } else if (!e.message.includes('status code 400') && !e.message.includes('status code 404')) {
      ElMessage.error(`${isEdit ? '修改' : '新增'}失败: ${e.message || '未知错误'}`)
    }
  }
}

// 表格多选
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id)
}

// 批量删除
function handleBatchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  deleteIds = selectedIds.value.join(',')
  deleteDialogVisible.value = true
}

// 删除
const deleteDialogVisible = ref(false)
let deleteId = null
let deleteIds = ''

function handleDelete(id) {
  deleteId = id
  deleteIds = id.toString()
  deleteDialogVisible.value = true
}

async function confirmDelete() {
  try {
    await request.delete(`/emps?ids=${deleteIds}`)
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    selectedIds.value = []
    fetchEmps()
  } catch (e) {
    console.error(e)
    ElMessage.error('删除失败: ' + (e.message || '未知错误'))
  }
}

// 新增头像上传功能
const fileInput = ref(null)

function triggerUpload() {
  fileInput.value.click()
}

// 处理文件上传
function handleFileChange(event) {
  const file = event.target.files[0]
  if (!file) return
  
  // 检查文件类型
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/jpg']
  if (!acceptedTypes.includes(file.type)) {
    ElMessage.error('只能上传JPG、JPEG或PNG格式的图片')
    event.target.value = '' // 清空选择
    return
  }
  
  // 检查文件大小（2MB = 2 * 1024 * 1024 bytes）
  const maxSize = 2 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('图片过大,上传失败')
    event.target.value = '' // 清空选择
    return
  }
  
  // 极度压缩图片 - 更小的尺寸和更低的质量
  compressImage(file, 0.3, 150, 150, (compressedBase64) => {
    // 检查压缩后的大小，如果仍然太大，提供警告
    const sizeKB = Math.round(compressedBase64.length / 1.37 / 1024)
    if (sizeKB > 2048) {
      ElMessage.error('图片过大,上传失败')
      event.target.value = '' // 清空选择
      return
    }
    form.image = compressedBase64
  })
}

// 图片压缩函数
function compressImage(file, quality, maxWidth, maxHeight, callback) {
  const reader = new FileReader()
  reader.onload = (e) => {
    const img = new Image()
    img.onload = () => {
      // 计算压缩后的尺寸，保持宽高比
      let width = img.width
      let height = img.height
      
      if (width > maxWidth) {
        height = Math.round(height * maxWidth / width)
        width = maxWidth
      }
      
      if (height > maxHeight) {
        width = Math.round(width * maxHeight / height)
        height = maxHeight
      }
      
      // 创建canvas进行压缩
      const canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      
      const ctx = canvas.getContext('2d')
      ctx.fillStyle = '#FFFFFF' // 白色背景
      ctx.fillRect(0, 0, width, height)
      ctx.drawImage(img, 0, 0, width, height)
      
      // 强制转换为JPEG格式（通常比PNG小）
      let compressedBase64
      if (file.type === 'image/png') {
        compressedBase64 = canvas.toDataURL('image/jpeg', quality)
      } else {
        compressedBase64 = canvas.toDataURL(file.type, quality)
      }
      
      // 输出压缩前后大小对比
      console.log('原始图片大小:', Math.round(e.target.result.length / 1.37 / 1024), 'KB')
      console.log('压缩后图片大小:', Math.round(compressedBase64.length / 1.37 / 1024), 'KB')
      
      callback(compressedBase64)
    }
    img.src = e.target.result
  }
  reader.readAsDataURL(file)
}
</script>

<style scoped>
.emp-manage-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}
.page-title {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}
.blue-bar {
  display: inline-block;
  width: 4px;
  height: 22px;
  background: #1890ff;
  margin-right: 8px;
  border-radius: 2px;
}
.search-area {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}
.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}
.add-btn {
  margin-left: 0;
}
.plus {
  font-size: 18px;
  margin-right: 2px;
}
.action-btn {
  margin: 0 8px;
  cursor: pointer;
}
.action-btn:hover {
  text-decoration: underline;
}
.action-btn.edit {
  color: #4b6ac9; /* 蓝色 */
}
.action-btn.delete {
  color: #d73030; /* 红色 */
}
.dialog-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.experience-section {
  border-top: 1px solid #eee;
  padding-top: 16px;
  margin-top: 16px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.section-header h3 {
  margin: 0;
  font-size: 16px;
}
.experience-item {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #f9f9f9;
}
.exp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.exp-header h4 {
  margin: 0;
  font-size: 14px;
}
.date-separator {
  margin: 0 8px;
  display: inline-block;
}
.image-upload {
  display: flex;
  align-items: flex-start;
}
.image-preview {
  width: 100px;
  height: 100px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  cursor: pointer;
  background-color: #f5f7fa;
}
.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.avatar-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  width: 100%;
  height: 100%;
}
.avatar-placeholder .el-icon {
  font-size: 24px;
}
.delete-btn-col {
  display: flex;
  align-items: center;
  justify-content: center;
}
.image-tip {
  margin-top: 8px;
  padding: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
}
</style> 